<template>
  <div class="form-components">
    <el-form
      ref="refName"
      :model="form"
      :rules="rules"
      :label-width="_formOptions.labelWidth"
      :size="_formOptions.size"
      :draggable="_formOptions.draggable"
      :showClose="_formOptions.showClose"
      :scroll-to-error="_formOptions.scrollToError"
      :disabled="_formOptions.disabled"
      :status-icon="_formOptions.statusIcon"
      :inline-message="_formOptions.inlineMessage"
      :show-message="_formOptions.showMessage"
      :require-asterisk-position="_formOptions.requireasteriskPosition"
      :hide-required-asterisk="_formOptions.hideRequiredasterisk"
      :label-position="_formOptions.labelPosition"
      :inline="_formOptions.inline"
      class="demo-ruleForm"
    >
       <slot name="formContaint"></slot>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
// 父组件传递数据
const props = defineProps({
  formObject: {
    default() {
      return {};
    },
    type: Object,
  },
  form: {
    default() {
      return {};
    },
    type: Object,
  },
  rules: {
    default() {
      return {};
    },
    type: Object,
  },
});

// 配置
const _formOptions = computed(() => {
  const option = {
    refName: '',
    labelWidth: '100px',
    size: 'large',
    draggable: false,
    showClose: true,
    scrollToError: true, // 当校验失败时，滚动到第一个错误表单项
    disabled: false, // 是否禁用该表单内的所有组件
    statusIcon: true, // 是否在输入框中显示校验结果反馈图标
    inlineMessage: false, // 是否以行内形式展示校验信息	
    showMessage: true, // 是否显示校验错误信息	
    requireasteriskPosition: 'left', // 星号的位置 (left、 right)
    hideRequiredasterisk: false, // 是否隐藏必填字段标签旁边的红色星号。
    labelPosition: 'right', //表单域标签的位置， 当设置为 left 或 right 时，则也需要设置 label-width 属性 (left、 right、top)
    inline: false
  };
  return Object.assign(option, props?.formObject);
});
// form 的ref名称
const refName = ref();

// 对整个表单的内容进行验证
const validateForm = (fn) => {
  refName.value.validate((valid) => {
    fn(valid);
  });
};

// 重置该表单项，将其值重置为初始值，并移除校验结果
const resetFieldsForm = () => {
  refName.value.resetFields();
};

// 验证具体的某个字段
const validateFieldForm = (key, fn) => {
  refName.value.validateField(key, (valid) => {
    fn(valid);
  });
};

// 清理某个字段的表单验证信息
const clearValidateForm = (key) => {
  refName.value.clearValidate(key);
};

defineExpose({
  validateForm: validateForm,
  resetFieldsForm: resetFieldsForm,
  validateFieldForm: validateFieldForm,
  clearValidateForm: clearValidateForm
});

</script>

<style lang="scss" scope>
.form-components {
  width: 100%;
}
</style>
